// pages/commonPage/benefitCardDetails/benefitCardDetails.js
var popup = require('../../../utils/popupUtils.js');
var netWork = require('../../../utils/netWork.js');
let isClick = true;
//选择城市
var show = false;
var addressInfo = {};
var item = {};
var model = require('../../../model/model.js')
var popup = require('../../../utils/popupUtils.js');
import {
    requestSubscribeMessage
} from "../../../utils/wxapi";
import {
    isShowReminderOfExpired
} from "../../../utils/publicMethods";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        imagesUrl: getApp().globalData.imagesUrl,
        back: true, //返回上个页面
        home: false, //返回首页
        data: "",
        materialInfo: {}, //邮寄信息
        address: '请选择地区', //地区文字显示
        item: { //城市选择器信息
            show: show
        },
        addressMsg: '', //详细地址
        formValue: {}, //form表单邮寄信息
        isShowEntityPopup: false, //是否显示实物弹窗
        redEnvelopes: 0, //红包
        entityData: {}, //实物弹窗奖励信息
        isShowEntityTips: false, //实物领取成功提示
        tanban_big_bg: getApp().globalData.imagesUrl + '/jingdianPage/tanban_big_bg1.png',
        handFlag:false,
        prizeOrderId:"",
        entryMode:"",//是哪个页面进入的（只区分页面不区分分支  prizeRecord是中奖记录 strongFragrance是浓香分支）
        entryModeDataIndex:0
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.data.prizeOrderId = options.prizeOrderId;
        this.data.entryMode = options.entryMode;
        this.data.entryModeDataIndex = options.entryModeDataIndex;
        if(options.userId){
            wx.setStorageSync('userId', options.userId);
        }
        if (options.userType) {
            wx.setStorageSync('userType', options.userType);
        }
        if(options.entryMode == 'remind'){
            if (wx.getStorageSync('userId') == '' || wx.getStorageSync('userId') == null || wx.getStorageSync('userId') == undefined) {
                let data = {
                    prizeOrderId:options.prizeOrderId,
                    entryMode:options.entryMode
                }
                wx.setStorageSync('benefitCardDetails', data);
                wx.redirectTo({
                    url: '/pages/webview/webview?type=fullPath&intoType=/pages/commonPage/benefitCardDetails/benefitCardDetails'
                })
                return;
            }
        }
        let rs =  wx.getStorageSync('benefitCardDetails');
        if(rs){
            this.data.prizeOrderId = rs.prizeOrderId;
            this.data.entryMode = rs.entryMode;
            wx.removeStorageSync('benefitCardDetails');
        }
        try {
            const {
                SDKVersion = ''
            } = wx.getSystemInfoSync();
            // 获取系统信息
            const that = this;
            wx.getSystemInfo({
                success: function (res) {
                    that.setData({
                        screenHeight: res.screenHeight - res.statusBarHeight - 50
                    });
                }
            });
            const compatibility = util.compareVersion(SDKVersion, '2.2.2');
            log.info(compatibility)
            if (compatibility == -1) {
                wx.showModal({
                    content: '您的微信版本过低，请升级后再来吧~',
                    confirmText: '我知道了',
                    showCancel: false
                });
                return;
            }
        } catch (e) {}
        //高度处理
        let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
        this.setData({
            topHeight: topHeight,
            icon: wx.getStorageSync('productType') == 4 || wx.getStorageSync('productType') == 5 ? 'xinyouranPage/loading_logo' : 'common/loading',
        });
        let m = wx.getStorageSync('materialInfo');
        if (m) {
            this.setData({
                materialInfo: m,
                address: m.receiveProvinceName + ' ' + m.receiveCityName + ' ' + m.receiveDistrictName,
                color: true,
                addressMsg: m.receiveAddress
            })
            addressInfo = this.data.materialInfo;
        } else {
            let userPhone = wx.getStorageSync('userPhone');
            let m1 = {};
            if (userPhone != "" && userPhone != null && userPhone != undefined) {
                m1['receivePhone'] = userPhone;
            }
            this.setData({
                materialInfo: m1
            })
        }
        this.getData()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function (e) {
        var that = this;
        //请求数据
        model.updateAreaData(that, 0, e);
    },
    getData() {
        let that = this;
        this.isLoading(true, "正在加载...")
        netWork.POST_Json('customerPrizeSubjoin/info', {
            data: {
                userId: wx.getStorageSync('userId'),
                prizeOrderId: that.data.prizeOrderId
            },
            success: function (res) {
                that.isLoading(false)
                if (res.data.retCode == "0000") {
                    that.data.entityData = {
                        prizeUrl:res.data.data.subjoinPrizeUrl,
                        prizeName:res.data.data.subjoinPrizeName,
                        prizeEndTime:res.data.data.prizeEndTime,
                    }
                    that.setData({
                        data: res.data.data,
                        entityData: that.data.entityData
                    })
                }else{
                    wx.showToast({
                        title: res.data.data.msg,
                        icon: 'none'
                    })
                }
            },
            fail: function () {
                that.isLoading(false);
            }
        })
    },
    handlerGobackClick() {
        let pages = getCurrentPages(); //当前页面
        let prevPage = pages[pages.length - 2]; //上一页面
        //浓香分支从权益卡详情页返回中奖页需要显示下个带有价值奖励按钮上的小手
        if (this.data.entryMode == 'strongFragrance') {
            popup.setHandFlag(prevPage);
        }
        if(this.data.entryMode == 'remind'){
            wx.redirectTo({
                url: '/pages/prizeRecord/prizeRecord',
            })
        }else{
            wx.navigateBack({
                delta: 1
            });
        }
    },
    isLoading(isLoading, loadingText) {
        this.setData({
            isLoading: isLoading,
            loadingText: loadingText
        })
    },
    setstatus() {
        if (this.data.data.status == 3) {
            this.setData({
                isShowEntityPopup: true
            })
        } else {
            this.updateOrder()
        }
    },
    updateOrder: function (event) {
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 3000); //3秒内不能重复点击
        }
        const that = this;
        wx.showModal({
            title: '提示',
            content: '确认收到货了吗？',
            success: function (sm) {
                if (sm.confirm) {
                    that.isLoading(true, "加载中...");
                    //兑奖
                    netWork.POST('confirmCustomerSubjoinPrize', {
                        data: {
                            userId: wx.getStorageSync('userId'),
                            prizeOrderId: that.data.data.prizeOrderId
                        },
                        success: function (res) {
                            that.isLoading(false)
                            if (res.data.retCode == undefined) {
                                that.isLoading(false)
                                wx.showToast({
                                    title: '操作失败',
                                    icon: 'error'
                                })
                                return;
                            }
                            if (res.data.retCode == "0000") {
                                wx.showToast({
                                    title: '操作成功',
                                    icon: 'success'
                                })
                                //更新该prizeOrderid对应的状态
                                that.data.data.status = '14';
                                that.setData({
                                    data: that.data.data
                                })
                                let pages = getCurrentPages(); //当前页面
                                let prevPage = pages[pages.length - 2]; //上一页面
                                prevPage.data.prizeList[that.data.entryModeDataIndex].status = '14'; //更新为领取成功
                                prevPage.setData({
                                    prizeList: prevPage.data.prizeList,
                                })
                            } else {
                                if(res.data.retCode == "10029"){
                                    let productType = wx.getStorageSync('productType');
                                    let error_url = productType == 4 ? '../../xinyouranPage/prompt/prompt' : productType == 1 ? '../../jingdianPage/prompt/prompt' : productType == 2 ? '../../prompt/prompt' : productType == 3 ? '../../ruiPage/prompt/prompt' : '../../xinyouranPage/xinyouranHighPage/prompt/prompt';
                                    wx.redirectTo({
                                        url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                                    }) 
                                }else{
                                    wx.showToast({
                                        title: '操作失败',
                                        icon: 'error'
                                    })
                                }
                            }
                        },
                        fail: function () {
                            that.isLoading(false)
                            wx.showToast({
                                title: '操作失败',
                                icon: 'error'
                            })
                        }
                    });
                } else if (sm.cancel) {
                    return;
                }
            }
        })
    },
    //点击选择城市按钮显示picker-view
    translate: function (e) {
        console.log('点击了')
        model.animationEvents(this, 0, true, 400);
    },
    //城市隐藏picker-view
    hiddenFloatView: function (e) {
        model.animationEvents(this, 200, false, 400);
        if (e.target.dataset.id == '555') {
            return;
        }
        if (this.data.address == '请选择省/市/区' || JSON.stringify(addressInfo) == '{}' || (this.data.item.value[0] == 0 && this.data.item.value[1] == 0 && this.data.item.value[2] == 0)) {
            addressInfo = {
                "receiveProvinceId": '110000',
                "receiveCityId": '110100',
                "receivceDistrictId": '110101',
                "receiveProvinceName": '北京市',
                "receiveCityName": '北京市',
                "receiveDistrictName": '东城区'
            };

        }
        this.setData({
            address: addressInfo.receiveProvinceName + ' ' + addressInfo.receiveCityName + ' ' + addressInfo.receiveDistrictName,
        })
        popup.receivePrizeHand(this);
    },
    //城市滑动事件
    bindChange: function (e) {
        model.updateAreaData(this, 1, e);
        item = this.data.item;
        addressInfo = {
            "receiveProvinceId": item.provinces[item.value[0]].id,
            "receiveCityId": item.citys[item.value[1]].id,
            "receivceDistrictId": item.countys[item.value[2]].id,
            "receiveProvinceName": item.provinces[item.value[0]].name,
            "receiveCityName": item.citys[item.value[1]].name,
            "receiveDistrictName": item.countys[item.value[2]].name
        };
    },
    //表单提交按钮,校验
    formSubmit: function (e) {
        //防止重复点击或者点击过快
        console.log("点击了");
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 5000); //3秒内不能重复点击
        }
        let userName = e.detail.value.userName;
        let phone = e.detail.value.phone;
        let detailAddress = e.detail.value.detailAddress;
        if (userName.trim() == "") {
            wx.showToast({
                title: '请输入收件人姓名',
                icon: 'none'
            })
            return;
        }
        if (userName.length > 20) {
            wx.showToast({
                title: '收件人姓名不能超过20个文字',
                icon: 'none'
            })
            return;
        }
        if (phone.trim() == "") {
            wx.showToast({
                title: '请输入手机号码',
                icon: 'none'
            })
            return;
        }

        let a = /^1\d{10}$/;
        if (!a.test(phone)) {
            wx.showToast({
                title: '请输入正确的手机号码',
                icon: 'none'
            })
            return;
        }
        if (this.data.address == '请选择地区') {
            wx.showToast({
                title: '请选择地区',
                icon: 'none'
            })
            return;
        }
        if (detailAddress.trim() == "") {
            wx.showToast({
                title: '请输入详细地址',
                icon: 'none'
            })
            return;
        }
        if (detailAddress.length > 60) {
            wx.showToast({
                title: '详细地址不能超过60个文字',
                icon: 'none'
            })
            return;
        }
        this.setData({
            formValue: e.detail.value,
            addressMsg: detailAddress
        })
        let materialInfo = {};
        materialInfo['receiveProvinceId'] = addressInfo.receiveProvinceId;
        materialInfo['receiveCityId'] = addressInfo.receiveCityId;
        materialInfo['receivceDistrictId'] = addressInfo.receivceDistrictId;
        materialInfo['receiveProvinceName'] = addressInfo.receiveProvinceName;
        materialInfo['receiveCityName'] = addressInfo.receiveCityName;
        materialInfo['receiveDistrictName'] = addressInfo.receiveDistrictName;
        materialInfo['receiveName'] = userName;
        materialInfo['receivePhone'] = phone;
        materialInfo['receiveAddress'] = detailAddress;
        console.info(materialInfo);
        wx.setStorageSync('materialInfo', materialInfo)
        popup.receiveBenefitCard(this, netWork, addressInfo,this.data.data.prizeOrderId);
    },
    //实物弹窗判断姓名输入框是否有值显示隐藏小手
    userName(e) {
        popup.setMaterialInfoAndIsHand(1, this, e.detail.value);
    },
    userPhone(e) {
        popup.setMaterialInfoAndIsHand(2, this, e.detail.value);
    },
    userDetailAddress(e) {
        popup.setMaterialInfoAndIsHand(3, this, e.detail.value);
    },
    //关闭实物弹窗
    async closeEntityPopup(e) {
        this.setData({
            isShowEntityPopup: false
        })
        let flag = await isShowReminderOfExpired(this.data.data.prizeOrderId);
        if (flag) {
            requestSubscribeMessage(this.data.data.prizeOrderId);
        }
    },
    //关闭实物领取成功提示
    async closeEntityTips() {
        this.setData({
            isShowEntityTips: false
        })
    }
})